/**
 * 删除上传的图片
 */
function deleteCover(value) {
    $("#" + value).remove();
}

/**
 * 会员
 */

define([
    'jquery',
    'baseUtils',
    'base',
    'msgTool',
    'css!global/plugins/wangEditor/wangEditor.min.css',
    'plugins/wangEditor/wangEditor.min',
    'css!global/plugins/fileInput/fileinput.min.css',
    'plugins/fileInput/fileinput.min',
    'plugins/bootstrap-table/bootstrap-table',
    "plugins/bootstrap-dialog/bootstrap-dialog",
    "css!global/plugins/bootstrap-dialog/bootstrap-dialog.css"
], function ($, baseUtils, base, msgTool, _, E, _, _, _, BootstrapDialog) {
    //默认加载基础库
    base();
    //执行
    return {

        /**
         * 列表
         */
        list: function () {

            var myTable = $('#userProjectList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'api.json'})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    winModal("编辑", row);
                },
                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '项目',
                        nameValue: row.title,
                        url: '/user/project/status/action'
                    });
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '项目',
                        nameValue: row.title,
                        url: '/user/project/delete/action'
                    });
                }
            };

            //table表格
            myTable.bootstrapTable({
                url: 'api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                // queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [{ // 列设置
                    field: 'state',
                    checkbox: true // 使用复选框
                },
                    {
                        field: 'id',
                        title: '编号'
                    }, {
                        field: 'title',
                        title: '项目标题',
                        formatter:function (value,row) {
                            return '<a href="/user/project/view/'+row.id+'" target="_blank">'+value+'</a>';
                        }
                    }, {
                        field: 'amount',
                        title: '预算金额',
                        formatter: function (value) {
                            return value + "元";
                        }
                    }, {
                        field: 'duration',
                        title: '预计工期',
                        formatter: function (value) {
                            return value + "天";
                        }
                    },
                    {
                        field: 'projectStatus',
                        title: '项目状态',
                        formatter: function (value) {
                            var result = null;
                            switch (value) {
                                case 0:
                                    result = "<span class=\"text text-default\">编辑中</span>";
                                    break;
                                case 1:
                                    result = "<span class=\"text text-primary\">已提交</span>";
                                    break;
                                case 2:
                                    result = "<span class=\"text text-danger\">被退回</span>";
                                    break;
                                case 3:
                                    result = "<span class=\"text text-warning\">招标中</span>";
                                    break;
                                case 4:
                                    result = "<span class=\"text text-info\">实施中</span>";
                                    break;
                                case 5:
                                    result = "<span class=\"text text-success\">已完成</span>";
                                    break;
                                case 6:
                                    result = "<span class=\"text text-default\">异常</span>";
                                    break;
                                default:
                                    result = "<span class=\"text text-primary\">未知</span>";
                                    break;
                            }
                            return result;
                        }
                    }, {
                        field: 'updateTime',
                        title: '更新时间'
                    }, {
                        field: 'beginTime',
                        title: '开工时间'
                    }, {
                        field: 'status',
                        title: '状态',
                        align: 'center',
                        formatter: function (value) {
                            if (value === 1) {
                                return '<span class="label label-success">正常</span>';
                            } else {
                                return '<span class="label label-danger">已禁</span>';
                            }
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });


        },

        /**
         * 查看
         */
        view: function () {

        },

        /**
         *编辑保存
         */
        save: function () {
            /**
             * 富文本编辑器
             */
            var editor = new E('#myEditer');
            var deails = $("textarea[name='intro']");
            // 监控变化，同步更新到 textarea
            editor.customConfig.onchange = function (html) {
                deails.text(html);
            };
            // 配置服务器端地址
            editor.customConfig.uploadImgServer = '/common/uploader/index';
            // 将图片大小限制为 30M
            editor.customConfig.uploadImgMaxSize = 30 * 1024 * 1024;
            // 限制一次最多上传 5 张图片
            editor.customConfig.uploadImgMaxLength = 50;
            // 上传文件名，类似于input>type=file>name
            editor.customConfig.uploadFileName = 'files';
            // 将 timeout 时间改为 20s
            editor.customConfig.uploadImgTimeout = 20000;
            // 自定义上传参数
            editor.customConfig.uploadImgParams = {
                filesType: 2
            };
            editor.create();

            /**
             * 文件上传
             */
            $("#fileUploader").fileinput({
                //设置语言
                language: 'zh',
                //上传的地址
                uploadUrl: '/common/uploader/index',
                method: 'post',
                msgPlaceholder: '请选择图片，最多可上传10张。',
                //附加属性(0图片，1文件)
                uploadExtraData: {filesType: 1},
                //上传类型
                allowedFileExtensions: ['jpg', 'gif', 'png', 'jpeg', '7z', 'rar', 'zip', 'doc', 'docx', 'xlsx', 'xls', 'pdf'],
                //是否显示图片展示框
                showPreview: false,
                //是否显示上传按钮
                showUpload: true,
                showCancel: false,
                //是否显示上传输入框
                showCaption: true,
                //是否显示删除键
                showRemove: true,
                //浏览图标
                browseIcon: '<i class="iconfont icon-wenjianjia"></i>&nbsp;',
                //浏览样式
                browseClass: 'btn btn-success btn-outline',
                //上传图标
                uploadIcon: '<i class="iconfont icon-upload"></i>&nbsp;',
                //上传样式
                uploadClass: 'btn btn-success btn-outline',
                //移除图标
                removeIcon: '<i class="iconfont icon-remove"></i>&nbsp;',
                //移除样式
                removeClass: 'btn btn-info btn-outline',
                //单位为kb，(30M)如果为0表示不限制文件大小
                maxFileSize: 30720,
                //错误显示位置
                elErrorContainer: "#file-upload-error",
                //错误显示位置节点样式
                msgErrorClass: 'alert alert-block alert-danger',
                //验证数量
                validateInitialCount: true
            }).on("fileuploaded", function (event, data) {
                $("#notAttr").remove();
                if (data.response !== null && data.response.status) {
                    $("#file-upload-success>table>tbody").append("<tr id=\"" + data.response.nodeId + "\"><td><input type='hidden' name='attachList' value=\"" + data.response.url + "##" + data.response.size + "\"><a target=\"_blank\" href=\"" + data.response.domain + data.response.url + "\">" + data.response.name + "</a></td><td>" + data.response.size + "</td><td><button type='button' class=\"btn btn-xs btn-danger deletetCover\" onclick=\"deleteCover('" + data.response.nodeId + "')\">删除</button></td></tr>");
                } else {
                    $("#file-upload-error").text(data.response.message);
                }
            });
          
                       
            $("#saveProjectForm").validate({
                rules: {
                 ignore:"",
                 cateList:{
                		 required: true
                	},
              	  title: {
                        required: true
                    },
                    amount: {
                        required: true,
                        digits: true
                    },
                    duration: {
                        required: true,
                        digits: true
                    },
                    peopleNumber: {
                        required: true,
                        digits: true
                    },
                    workAddress: {
                        required: true,
                        rangelength: [2, 100]
                    },
                    beginTime: {
                        required: true,
                        date: true
                    },
                    description: {
                        required: true
                    },
                    intro:{
                  	  required: true,
                  	 rangelength: [10, 100]
                    }
                },
                messages: {
                  cateList:{
                		 required: errorIcon +"项目分类不能为空"
                 },
              	  title: {
                        required: errorIcon + "标题不能为空"
                    },
                    amount: {
                        required: errorIcon + "预算金额不能为空",
                        digits: $.validator.format(errorIcon + "只能输入数字。")
                    },
                    duration:{
                  	  required: errorIcon + "预算工期不能为空",
                  	  digits: $.validator.format(errorIcon + "只能输入数字。")
                    },
                    peopleNumber: {
                  	  required: errorIcon + "不能为空",
                  	  digits: $.validator.format(errorIcon + "只能输入数字。")
                    },
                    workAddress: {
                        required: errorIcon + "详细地址不能为空",
                        rangelength: $.validator.format(errorIcon + "字数在2-100个之间。")
                    },
                    beginTime: {
                        required: errorIcon + "开始时间不能为空",
                        birthday: $.validator.format(errorIcon + "格式错误，范例：2017-08-10")
                    },
                    description: {
                        required: errorIcon + "不能为空"
                    },
                    intro: {
                        required: errorIcon + "不能为空"
                    }
                }
            });

            /**
             * 提交项目
             */
            $("#submitProject").on('click', function () {
              var valid = $("#saveProjectForm").valid();
              if (valid) {
                $.baseUtils.ajax({
                    url: "/user/project/save/action",
                    data: $("#saveProjectForm").serialize(),
                    context: "项目",
                    text: "提交",
                    skip: "/user/project/list",
                    skipTime: 3000
                });
               }
            })


        },

        /**
         *申请列表
         */
        applyList: function () {
            var myTable = $('#userApplyList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'api.json'})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    winModal("操作", row);
                },
                'click .audit': function (e, value, row) {
                    if (row.applyStatus === 0) {
                        BootstrapDialog.show({
                            title: "申请审批",
                            message: $('<div></div>').load('form.html'),
                            type: BootstrapDialog.TYPE_DEFAULT,
                            closable: true,
                            draggable: true,
                            //点击空白不消失
                            closeByBackdrop: false,
                            //ESC取消禁用
                            closeByKeyboard: true,
                            buttons: [{
                                label: '取消',
                                cssClass: 'btn-white',
                                icon: 'fa fa-times',
                                action: function (dialogItself) {
                                    dialogItself.close();
                                }
                            }, {
                                label: '拒绝',
                                cssClass: 'btn-primary',
                                icon: 'fa fa-plus-square',
                                action: function (dialogItself) {
                                    execute(dialogItself, 2);
                                }
                            }, {
                                label: '通过',
                                cssClass: 'btn-success',
                                icon: 'fa fa-cloud-upload',
                                action: function (dialogItself) {
                                    execute(dialogItself, 1);
                                }
                            }],
                            onshown: function (dialog) {
                                if (row !== null) {
                                    $('#id').val(row.id);
                                }
                            }
                        });
                        var execute = function (dialogItself, type) {
                            $.ajax({
                                url: 'action.json',
                                method: "POST",
                                dataType: "json",
                                data: {
                                    statusMessage: $("#statusMessage").val(),
                                    applyStatus: type,
                                    id: row.id
                                },
                                success: function (data) {
                                    if (data.success) {
                                        msgTool.success(type === 1 ? "审核成功操作完成" : "审核拒绝操作完成", "信息提示");
                                        myTable.bootstrapTable('refresh', {url: 'api.json'});
                                        dialogItself.close();
                                        return false;
                                    } else {
                                        msgTool.error("警告！" + data.msg, "错误提示");
                                        dialogItself.close();
                                        return false;
                                    }
                                },
                                error: function (jqXHR) {
                                    msgTool.error(jqXHR.status + " (" + jqXHR.statusText + ")", "错误提示");
                                    dialogItself.close();
                                    return false;
                                }
                            });
                        };
                    } else {
                        msgTool.error("当前申请已经审批过了", "信息提示");
                    }

                }

            };

            //table表格
            myTable.bootstrapTable({
                url: 'api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                // queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [{ // 列设置
                    field: 'state',
                    checkbox: true // 使用复选框
                },
                    {
                        field: 'id',
                        title: '编号'
                    }, {
                        field: 'projectTitle',
                        title: '项目标题'
                    }, {
                        field: 'applyUserName',
                        title: '申请人'
                    }, {
                        field: 'amount',
                        title: '预算金额',
                        formatter: function (value) {
                            return value + "元";
                        }
                    }, {
                        field: 'duration',
                        title: '预计工期',
                        formatter: function (value) {
                            return value + "天";
                        }
                    },
                    {
                        field: 'applyStatus',
                        title: '申请状态',
                        // 0申请中，1申请通过，2申请失败，3申请取消
                        formatter: function (value) {
                            var result = null;
                            switch (value) {
                                case 0:
                                    result = "<span class=\"text text-default\">申请中</span>";
                                    break;
                                case 1:
                                    result = "<span class=\"text text-success\">申请通过</span>";
                                    break;
                                case 2:
                                    result = "<span class=\"text text-danger\">申请失败</span>";
                                    break;
                                case 3:
                                    result = "<span class=\"text text-warning\">申请取消</span>";
                                    break;
                                default:
                                    result = "<span class=\"text text-primary\">未知</span>";
                                    break;
                            }
                            return result;
                        }
                    }, {
                        field: 'updateTime',
                        title: '申请时间'
                    }, {
                        field: 'status',
                        title: '状态',
                        align: 'center',
                        formatter: function (value) {
                            if (value === 1) {
                                return '<span class="label label-success">正常</span>';
                            } else {
                                return '<span class="label label-danger">已禁</span>';
                            }
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });


        }
    }
});


